
package br.unirio.bsi.dsw.AuctionSite.action;

import flexjson.JSONSerializer;

import org.apache.struts.action.*;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.unirio.bsi.dsw.AuctionSite.beans.loginForm;
import br.unirio.bsi.dsw.AuctionSite.model.dao.GenericDAO;

import br.unirio.bsi.dsw.AuctionSite.beans.formBeanO;
import br.unirio.bsi.dsw.AuctionSite.beans.ofertaForm;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;

public class ofertaAction extends Action 
{
  public static final long MILLISECS_PER_MINUTE = 60*1000;
  public static final long MILLISECS_PER_HOUR   = 60*MILLISECS_PER_MINUTE;
  public static final long MILLISECS_PER_DAY = 24*MILLISECS_PER_HOUR;  
  
  @Override
  public ActionForward execute(ActionMapping mapping, 
                               ActionForm form,
                               HttpServletRequest request, 
                               HttpServletResponse response) throws Exception 
  {      
    // pega a session
    HttpSession session = request.getSession();  
    
    // check logged
    loginForm lf = (loginForm)session.getAttribute("loginForm"); 
    if( lf == null || !lf.isLogged() )
      return null;
    
    // pega instancia do DAO    
    GenericDAO gD = GenericDAO.getInstance(getResources(request).getMessage("DB_NAME"));
    
    // copy
    ofertaForm oF = (ofertaForm)form;
            
    // parameter
    if( oF.getOperation() != null && 
        oF.getOperation().equals( ofertaForm.OPERATION_INSERT ) )
    {
      String selAlb = oF.getSelectedAlbum();
      if( selAlb != null && !selAlb.isEmpty() )
      {      
        // alloca nova oferta
        formBeanO oferta = new formBeanO();

        oferta.setIDUsuario(lf.getId());
        oferta.setIDAlbum( Integer.parseInt( selAlb ) );
        oferta.setOfferStart( new Timestamp( new java.util.Date().getTime() ) );
        oferta.setOfferDuration( Integer.parseInt( oF.getOfferDuration() ) );
        oferta.setBid( new BigDecimal(oF.getNewBid().replace(',' , '.' )) );
        oferta.setBuyout( new BigDecimal(oF.getNewBuyout().replace(',' , '.' )) );
        
        oferta.setBidOwner(0);
        oferta.setBuyoutOwner(0);

        // coloca no banco
        gD.insert( oferta );
      }
    }
    else
    if( oF.getOperation() != null && 
        oF.getOperation().equals( ofertaForm.OPERATION_BID ) )
    {
      formBeanO oferta = new formBeanO();
      
      oferta.setID( Integer.parseInt( oF.getSelectedOferta() ) );
      oferta.setBidOwner( lf.getId() );
      oferta.setBid( new BigDecimal(oF.getNewBid().replace(',' , '.' )) );
            
      // coloca no banco
      gD.update( oferta );
    }
    else
    if( oF.getOperation() != null && 
        oF.getOperation().equals( ofertaForm.OPERATION_BUYOUT ) )
    {
      formBeanO oferta = new formBeanO();
      
      oferta.setID( Integer.parseInt( oF.getSelectedOferta() ) );
      oferta.setBidOwner( lf.getId() );      
      oferta.setBuyoutOwner( lf.getId() );
         
      // coloca no banco
      gD.update( oferta );
    }
      
    // return listing
    String selPage = oF.getSelectedPage();
    String selArt = oF.getSelectedArtista();
    String selEst = oF.getSelectedEstilo();         
    String selAlb = oF.getSelectedAlbum();
    String search = oF.getSearch();
    
    if( selAlb != null && !selAlb.equals("") )
    {
      gD.retrieveAll( "SELECT DISTINCT o.*, b.nome as artistaNome, a.nome as albumNome, u.nome as usuarioNome, a.url as url " +
                      "FROM Oferta o, Album a, Artista b, Usuario u " +
                      "WHERE  o.idalbum = " + selAlb +
                      " AND   o.idalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = o.idusuario " +
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanO.class, oF.getOffers() );             
    }    
    else
    if( selEst != null && !selEst.equals("") ) 
    {        
      gD.retrieveAll( "SELECT DISTINCT o.*, b.nome as artistaNome, a.nome as albumNome, u.nome as usuarioNome, a.url as url  " +
                      "FROM Oferta o, Album a, Artista b, Usuario u, EstiloArtista ea " +
                      "WHERE  o.idalbum = a.id " +
                      " AND   ea.idestilo = " + selEst +
                      " AND   ea.idartista = a.idartista " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = o.idusuario " +                 
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanO.class, oF.getOffers() );             
    }
    else    
    if( selArt != null && !selArt.equals("") ) 
    {
      gD.retrieveAll( "SELECT DISTINCT o.*, b.nome as artistaNome, a.nome as albumNome, u.nome as usuarioNome, a.url as url  " +
                      "FROM Oferta o, Album a, Artista b, Usuario u " +
                      "WHERE  o.idalbum = a.id " +
                      " AND   b.id = " + selArt +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = o.idusuario " +                 
                      " ORDER BY a.nome ASC " +                            
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanO.class, oF.getOffers() );             
    }
    else    
    if( search != null && !search.equals("") ) 
    {
      gD.retrieveAll( "SELECT DISTINCT o.*, b.nome as artistaNome, a.nome as albumNome, u.nome as usuarioNome, a.url as url  " +
                      "FROM Oferta o, Album a, Artista b, Usuario u, Musica m " +
                      "WHERE  o.idalbum = a.id " +
                      " AND   b.id = a.idartista " +   
                      " AND   u.id = o.idusuario " +   
                      " AND   m.idalbum = a.id " +              
                      " AND  (a.nome ~* '"+ search + "'  " +
                      "    OR b.nome ~* '"+ search + "'  " +
                      "    OR m.nome ~* '"+ search + "') " +             
                      " ORDER BY a.nome ASC " +
                      "OFFSET " + selPage +              
                      " LIMIT 35",       
                      formBeanO.class, oF.getOffers() );             
    }
    
    // create time left string
    for( formBeanO o : oF.getOffers() ) 
      o.setTimeLeft( getTimeLeft( o.getOfferStart(), o.getOfferDuration() ) );
                   
    String jsonOfertas = new JSONSerializer()
                            .exclude("class").exclude("IDArtista")
                            .serialize( oF.getOffers() );
    
    jsonOfertas = "({\"ofertas\":" + jsonOfertas + "})";
        
    response.getWriter().write( jsonOfertas );
    response.getWriter().flush();
    
    return null;
  }
  
  private String getTimeLeft( Timestamp offerStart, int offerDuration )
  {
    Date offerEnd = new Date( offerStart.getTime() + (offerDuration * MILLISECS_PER_HOUR) );
      
    Date now = new Date( new java.util.Date().getTime() );
    long dateDiff = offerEnd.getTime() - now.getTime();
    
    String timeLeft = "";
       
    if( dateDiff > MILLISECS_PER_DAY ) {
      timeLeft += dateDiff/MILLISECS_PER_DAY + " days ";
      dateDiff %= MILLISECS_PER_DAY;
    }    
    
    if( dateDiff > MILLISECS_PER_HOUR ) {
      timeLeft += dateDiff/MILLISECS_PER_HOUR + " hours ";
      dateDiff %= MILLISECS_PER_HOUR;
    }
    
    if( dateDiff > MILLISECS_PER_MINUTE ) {
      timeLeft += dateDiff/MILLISECS_PER_MINUTE + " min";
    }
        
    return timeLeft;
  }
}
